import { Service, BaseService, Context } from './Service'
import * as fs from 'fs'
import * as path from 'path'
import log from '../config/logger'

const serviceMap = new Map<string, Service>()

const files = fs.readdirSync(path.join(__dirname, 'impl'))
files.forEach(f => {
  const UserService = require(path.join(__dirname, 'impl', f))
  const service = UserService.default || UserService as Service
  serviceMap.set(service.serviceNo, service)
  log.info(`service ${f} with serviceNo: [${service.serviceNo}] loaded!`)
})

async function executeServiceInterface (ctx: Context, serviceInterfaceNo: string = ctx.header.service || '') {
  const serviceNo = serviceInterfaceNo.substr(0, 5)
  const service = serviceMap.get(serviceNo)

  if (service instanceof BaseService) {
    if (ctx.method.toUpperCase() !== 'POST') { ctx.throw(405) }
    log.info(`invoking service: ${serviceNo}`)
    ctx.serviceMap = serviceMap
    await service.service(serviceInterfaceNo, ctx)
  } else {
    ctx.throw(404, `service [${serviceInterfaceNo}] does not exists`)
  }
}

export default serviceMap

export {
  Service,
  BaseService,
  executeServiceInterface
}
